package base.join;

/**
 * @author chengzhang
 * 2021/8/24 17:55
 */
public class Join01 {

    /**
     * main 线程调用 线程thread01的 Join 方法后会被阻塞，当其它（thread02）线程调用了 main线程的interrupt 方法中断了 main线程时
     * main线程会抛出 InterruptedException异常而返回
     */
    public static void main(String[] args) {
        //thread01里执行死循环，主线程调用thread01的join方法阻塞自己等待线程thread01执行完毕，待thread02休眠1s后会调用主线程的
        // interrupt方法设置主线程的中断标志，从而在主线程中的thread01.join()会抛出InterruptedException异常
        //线程1
        Thread thread01 = new Thread(() -> {
            System.out.println("thread01 begin run!");
            for (; ; ) {

            }
        });

        //获取主线程
        final Thread mainThread = Thread.currentThread();

        Thread thread02 = new Thread(() -> {
            System.out.println("thread02 begin run!");
            try {
                System.out.println("thread02 1000");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //中断主线程
            System.out.println("mainThread interrupt");
            mainThread.interrupt();
        });

        //启动子线程
        thread01.start();
        System.out.println("thread01 start");

        //延迟1s启动线程
        thread02.start();
        System.out.println("thread02 start");

        //等待线程01执行结束
        try {
            System.out.println("thread01 join start");
            thread01.join();
            System.out.println("thread01 join end");
        } catch (InterruptedException e) {
            System.out.println("main thread:" + e);
        }
    }
}
